from PIL import Image
import argparse

ascii_char = list("$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'. ")

def get_char(r, g, b, alpha = 256):
    if alpha == 0:
        return ' '

    length = len(ascii_char)
    gray =  r * 299/1000 + g * 587/1000 + b * 114/1000

    index = int( gray * length / 256 ) % length

    return ascii_char[index]

def parse_arg():
    parser = argparse.ArgumentParser()
    parser.add_argument('i', help="input file")
    parser.add_argument('-o', default="./output", help="output ascii file")
    parser.add_argument('-w', type=int, default=40, help="output ascii width")

    return parser.parse_args()

if __name__ == '__main__':
    args = parse_arg()

    im = Image.open(args.i)
    print(im.size)
    w = args.w
    h = int(im.size[1] * args.w / im.size[0])
    im = im.resize((args.w,h), Image.NEAREST)

    print(h)
    text = []

    for x in range(h):
        for y in range(w):
            text.append(get_char(*im.getpixel((y,x))))
        text.append('\n')

    with open(args.o, 'w+') as f:
        f.writelines(''.join(text))

